package com.heima.comment.service.impl;

import apis.article.IArticleClient;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import apis.user.IUserClient;
import com.alibaba.fastjson.JSON;
import com.heima.comment.pojos.entity.ApCommentLike;
import com.heima.comment.pojos.entity.ApComment;
import com.heima.comment.service.CommentService;
import com.heima.model.article.pojos.ApArticleConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import com.heima.comment.dtos.CommentDto;
import com.heima.comment.pojos.vos.ApCommentVo;
import com.heima.common.constants.BehaviorConstans;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.message.Message;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ThreadLocalUtil;
import com.heima.verify.service.impl.VerifyMaterialServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import com.heima.model.comment.dtos.CommentLikeDto;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IUserClient iUserClient;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private VerifyMaterialServiceImpl verifyMaterialService;

    /**
     * 保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentDto dto) {
        //校验参数
        if (dto == null || dto.getArticleId() == null || StringUtils.isBlank(dto.getContent()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        //判断是否登录,登录才能评论
        Integer userId = ThreadLocalUtil.get();
        ResponseResult<ApUser> result = iUserClient.getUser(userId);
        ApUser user = result.getData();

        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断文章是否可以评论,远程调用获取文章配置
        Long articleId = dto.getArticleId();
        ResponseResult<ApArticleConfig> configResponseResult = iArticleClient.getConfig(articleId);
        ApArticleConfig config = configResponseResult.getData();
        if (config.getIsComment() == false)
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"文章不可评论");


        //评论字数小于140
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(555, "评论敲这么多字,脑子有泡啊");
        }

        //评论审核,wemedia端,如果不通过审核不能发布,监听审核信息,审核通过这边接收通过消息,再执行
        Map res = verifyMaterialService.VerifyText(dto.getContent());
        Integer type = (Integer) res.get("conclusionType");
        if (type == 2) {
            return ResponseResult.errorResult(555, "评论违规");
        }

        //发kafka去article,热点文章算分,添加到article数据库评论数量加一
        Message message = new Message(dto.getArticleId());
        message.setComment(1);
        kafkaTemplate.send(BehaviorConstans.HOT_ARTICLE_AGG_TOPIC, JSON.toJSONString(message));
        log.info("成功发送：{}", message);

        //保存评论到mongodb数据库
        ApComment apComment = new ApComment(IdWorker.getId());
        apComment.setAuthorId(userId);
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setAuthorName(user.getName());

        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 评论查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult viewComments(CommentDto dto) {
        //校验参数
        if (dto == null || dto.getArticleId() == null || dto.getMinDate() == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        //根据条件查询
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId())
                        .and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))//排序
                .limit(10);//每次加载十条

        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);

        //返回数据
        List<ApCommentVo> apCommentVos = new ArrayList<>();

        for (ApComment comment : apComments) {
            ApCommentVo commentVo = new ApCommentVo();
            BeanUtils.copyProperties(comment, commentVo);
            //远程调用查评论作者头像
            //先获取当前登录用户id
            Integer authorId = comment.getAuthorId();
            Integer userId = ThreadLocalUtil.get();

            ResponseResult result = iUserClient.getUser(authorId);
            ApUser apUser = (ApUser) result.getData();
            //设置评论作者头像
            commentVo.setImage(apUser.getImage());
            //查询当前登录用户是否点赞该评论,如果点赞了,评论内容高亮
            Query query1 = Query.query(Criteria.where("authorId").is(userId).and("commentId").is(commentVo.getId()));
            ApCommentLike isLike = mongoTemplate.findOne(query1, ApCommentLike.class);
            if (isLike != null)
                commentVo.setOperation(0);
            apCommentVos.add(commentVo);
        }
        return ResponseResult.okResult(apCommentVos);
    }


    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //校验参数
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        Integer userId = ThreadLocalUtil.get();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(dto.getCommentId())), ApComment.class);
        //点赞  数量+1
        if (apComment != null && dto.getOperation() == 0) {
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);

            //入库
            ApCommentLike apCommentLike = new ApCommentLike(IdWorker.getId());
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setAuthorId(userId);
            mongoTemplate.save(apCommentLike);
        } else {
            //取消点赞 数量-1
            int tmp = apComment.getLikes() - 1;
            tmp = tmp < 1 ? 0 : tmp;
            apComment.setLikes(tmp);
            mongoTemplate.save(apComment);
            //删除对应库中数据
            Query query = Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(userId));
            mongoTemplate.remove(query, ApCommentLike.class);
        }
        //封装返回
        Map<String, Object> result = new HashMap<>();
        result.put("likes", apComment.getLikes());
        return ResponseResult.okResult(result);
    }
}
